import { COMMON_API_BASE_URL } from '@/utils/request'

// 统一处理接口返回的图片或文件 URL (审批单详情 审批单 聊天记录)
export function ProcessingURL(url) {
  if (!url) return ''

  let setUrl = null

  if (url.startsWith('http://117.89.250.65:81/')) {
    setUrl = url.replace(
      'http://117.89.250.65:81',
      'https://cloud.mfarmers.com'
    )
  } else if (url.startsWith('https://cloud.mfarmers.com/')) {
    setUrl = url
  } else if (url.startsWith('http://121.229.203.227:81/')) {
    setUrl = url.replace(
      'http://121.229.203.227:81',
      'https://cloud.mfarmers.com'
    )
  } else if (!url.startsWith('http')) {
    setUrl = `${COMMON_API_BASE_URL}${url.startsWith('/') ? '' : '/'}${url}`
  } else {
    setUrl = url
  }

  return setUrl
}

// 通用图片预览方法(审批单详情 审批单)
export function ImgviewClick(item, img, val) {
  let imgList = []
  let index = 0

  // 确保图片的完整 URL
  const currentUrl = ProcessingURL(img?.url || img?.path)

  if (val === 'pl') {
    // 数组形式
    item?.forEach((aitem) => {
      if (aitem?.url || aitem?.path) {
        const fullUrl = ProcessingURL(aitem.url || aitem.path)
        imgList.push(fullUrl)
      }
    })
    index = imgList.findIndex((url) => url === currentUrl)
  } else {
    // 对象里有 value 数组形式
    const list = item?.value || item
    list?.forEach((aitem) => {
      if (aitem?.url || aitem?.path) {
        const fullUrl = ProcessingURL(aitem.url || aitem.path)
        imgList.push(fullUrl)
      }
    })
    index = imgList.findIndex((url) => url === currentUrl)
  }

  if (index === -1) index = 0

  uni.previewImage({
    current: index,
    urls: imgList,
  })
}

// 通用文件预览方法（图片、文档、下载）  (审批单详情 审批单)
export function FileViewClick(data, item, options = {}) {
  const { xtoken = '', userId = '' } = options
  // 获取文件后缀
  const ext = (item.name || item.filename || '').split('.').pop().toLowerCase()

  // 图片预览处理
  if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) {
    const imgList = data
      .filter((i) =>
        ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'].includes(
          (i.name || i.filename || '').split('.').pop().toLowerCase()
        )
      )
      .map(
        (i) =>
          ProcessingURL(i.url || i.path) || `${COMMON_API_BASE_URL}${i.path}`
      )

    const currentUrl =
      ProcessingURL(item.url || item.path) ||
      `${COMMON_API_BASE_URL}${item.path}`
    const index = imgList.indexOf(currentUrl)

    uni.previewImage({
      current: index >= 0 ? index : 0,
      urls: imgList,
    })
    return
  }

  // 文档、其他文件处理
  const strname = item.name || item.filename
  const strurl = item.url || item.path
  const typeList = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
  const icon = (strname.split('.').pop() || '').toLowerCase()

  let url = ''
  const fileName = encodeURIComponent(encodeURIComponent(strname)) // 双重编码
  const fileurl = encodeURIComponent(strurl) // 单次编码
  if (typeList.includes(icon)) {
    let previewUrl = ''
    if (xtoken) {
      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${
        item.nc_id || ''
      }&fileName=${fileName}&type=mobile&user=${userId}&url=${fileurl}`
    } else {
      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${userId}&url=${fileurl}`
    }
    const encodedData = encodeURIComponent(JSON.stringify({ previewUrl }))
    url = `/pages/chat/message/common/previewDoc?data=${encodedData}`
  } else {
    url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${item.formatSize}&url=${fileurl}`
  }

  uni.navigateTo({ url })
}
// 使用相机跳转
export function handleScanResult(result) {
  if (result == 'green-cloud-camera') {
    uni.reLaunch({ url: '/pages/watermarkCamera/index' })
  } else if (result == 'green-cloud-worklog') {
    uni.reLaunch({ url: '/pages/worklog/index?jumpTo=写日志' })
  } else if (result.includes('uploadPhoto')) {
    const queryStr = result.split('?')[1] || ''
    const queryArr = queryStr.split('&')
    let applyId = '',
      componentId = '',
      qrToken = ''

    queryArr.forEach((pair) => {
      const [key, value] = pair.split('=')
      if (key === 'apply_id') applyId = value
      if (key === 'component_id') componentId = value
      if (key === 'qrToken') qrToken = value
    })

    if (applyId || componentId || qrToken) {
      // #ifdef APP-PLUS
      uni.navigateTo({
        url: `/pages/watermark/components/home?source=homeIndex&apply_id=${applyId}&component_id=${componentId}&qrToken=${qrToken}`,
        animationType: 'none',
      })
      // #endif

      // #ifdef H5
      uni.navigateTo({
        url: `/pages/watermark/components/h5camera?source=h5homeIndex&apply_id=${applyId}&component_id=${componentId}&qrToken=${qrToken}`,
        animationType: 'none',
      })
      // #endif
    } else {
      uni.showToast({
        title: '二维码参数不完整',
        icon: 'none',
      })
    }
  } else {
    // #ifdef H5
    uni.navigateBack()
    // #endif
    uni.showToast({
      title: '未知二维码',
      icon: 'none',
    })
  }
}

/**
 * 通用文件预览方法（支持：图片、文档、其他文件）
 * @param {Object} item 当前点击的文件对象
 * @param {Object} options 可选参数
 * @param {Array} [options.fileList] 文件数组（用于图片预览时多图浏览）
 * @param {Object} [options.userStore] 用户信息 store
 * @param {String} [options.xtoken] 云端令牌
 */
export function viewFile(item, options = {}) {
  const { fileList = [], userStore, xtoken } = options

  const name = item.name || item.filename || ''
  const url = item.url || item.path || ''
  const ext = name.split('.').pop()?.toLowerCase()

  // ===== 图片处理 =====
  const imageExts = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg']
  if (imageExts.includes(ext)) {
    // 判断是否多图模式
    if (fileList.length > 0) {
      const imgList = fileList
        .filter((f) =>
          imageExts.includes(
            (f.name || f.filename || '').split('.').pop()?.toLowerCase()
          )
        )
        .map(
          (f) =>
            ProcessingURL?.(f.url || f.path) ||
            `${COMMON_API_BASE_URL}${f.path || f.url}`
        )
      const currentUrl = ProcessingURL?.(url) || `${COMMON_API_BASE_URL}${url}`
      const index = imgList.indexOf(currentUrl)
      uni.previewImage({ current: index, urls: imgList })
    } else {
      uni.previewImage({ urls: [url] })
    }
    return
  }

  // ===== 文档处理 =====
  const docExts = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
  const fileName = encodeURIComponent(encodeURIComponent(name)) // 双重编码
  const fileurl = encodeURIComponent(url) // 单次编码

  if (docExts.includes(ext)) {
    let previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${userStore?.user?.worker_id}&url=${fileurl}`
    if (xtoken) {
      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${
        item.nc_id || ''
      }&fileName=${fileName}&type=mobile&user=${
        userStore?.user?.worker_id
      }&url=${fileurl}`
    }
    const encodedData = encodeURIComponent(JSON.stringify({ previewUrl }))
    uni.navigateTo({
      url: `/pages/chat/message/common/previewDoc?data=${encodedData}`,
    })
    return
  }

  // ===== 其他文件处理 =====
  uni.navigateTo({
    url: `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${
      item.formatSize || item.size
    }&url=${fileurl}`,
  })
}

// 审批单下载、打印 h5环境
export function getdownloadFileH5(fileUrl, name, xtoken, worker_id) {
  let strname = name
  let strurl = fileUrl
  const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
  const str = strname.split('.')
  const icon = str[str.length - 1]
  const that = this
  let url = ''

  const fileName = encodeURIComponent(encodeURIComponent(strname)) // 双重编码
  const fileurl = encodeURIComponent(strurl) // 单次编码

  if (type.indexOf(icon) != -1) {
    let previewUrl = ''

    if (xtoken) {
      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${''}&fileName=${fileName}&type=mobile&user=${worker_id}&url=${fileurl}`
    } else {
      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${worker_id}&url=${fileurl}`
    }
    let encodedData = encodeURIComponent(JSON.stringify({ previewUrl }))
    url = `/pages/chat/message/common/previewDoc?data=${encodedData}`
  } else {
    url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${'0'}&url=${fileurl}`
  }

  uni.navigateTo({
    url: url,
  })
}
